#include "GameMessage.h"

GameMessage::~GameMessage()
{
    for (int i = 0; i < 12; ++i)
    {
        while (!msgs->empty())
        {
            delete[] msgs->front();
            msgs->pop_back();
        }
    }
}

void GameMessage::showMessage(const char *msg, int playerID)
{
    char *newmsg = new char[strlen(msg) + 1];
    strcpy(newmsg, msg);

    if (playerID < 0)
    {
        for (int i = 0; i < 12; ++i)
        {
            msgs[i].push_back(newmsg);
        }
    }
    else
    {
        msgs[playerID].push_back(newmsg);
    }
}

void GameMessage::render(SDL_Renderer *renderer)
{
    SDL_Color color = {0xff, 0xff, 0xff};
    SDL_Rect rc = msg_rect;
    for (auto it = msgs->begin(); it != msgs->end(); ++it)
    {
        SDL_Surface *msg_sur = TTF_RenderUTF8_Blended(Static::default_font, *it, color);
        SDL_Texture *msg_tex = SDL_CreateTextureFromSurface(renderer, msg_sur);

        TTF_SizeUTF8(Static::default_font, *it,&rc.w,&rc.h);
        SDL_RenderCopy(renderer,msg_tex,nullptr,&rc);
        SDL_DestroyTexture(msg_tex);
        SDL_FreeSurface(msg_sur);
        rc.y += rc.h;
    }
}

int GameMessage::update(real delta)
{
    for (int i = 0; i < 12; ++i)
    {
        if (msgs[i].size() > 10)
        {
            delete[] msgs[i].front();
            msgs[i].pop_front();
        }
    }
    return 0;
}
